package com.iclient.job;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iclient.dao.mapper.SearchTagMapper;
import com.iclient.dao.model.SearchTag;
import com.iclient.dao.model.WbUser;
import com.iclient.dao.service.WbUserService;
import com.plugins.http.WbSearchUtils;
import com.plugins.server.MQServer;

@Repository
public class SearchJob {
	
	@Autowired
	private SearchTagMapper searchTagMapper;
	@Autowired
	private WbUserService wbUserService;
	
	@Scheduled(cron="0 */5 * * * ?")
	public void searchByTag() throws InterruptedException{
		List<SearchTag> tags = searchTagMapper.findTags();
		if(!CollectionUtils.isEmpty(tags)){
			for(SearchTag searchTag : tags){
				try{
					searchTag.setBeginTime(new Date());
					Integer pagesize = WbSearchUtils.searchUserByKeyword(searchTag.getTag());
					searchTag.setPagesize(pagesize);
					searchTag.setFinish(true);
					searchTagMapper.updateTagBy(searchTag);
					Integer pagenum = 5;
					if(pagesize <= pagenum){
						pagenum = pagesize;
					}
					Integer page = pagesize -pagenum + 1;
					for(;page <= pagesize; page ++){
						List<Map<String, Object>> users = WbSearchUtils.searchUserByKeyword(searchTag.getTag(), page);
						if(!CollectionUtils.isEmpty(users)){
							for(Map<String, Object> map : users){
								WbUser wbUser = JSONObject.toJavaObject(JSON.parseObject(JSONObject.toJSONString(map)), WbUser.class);
								wbUser.setCreateTime(new Date());
								wbUser.setAttention(false);
								if(wbUser.getMainpage().equals(wbUser.getAddUrl())){
									wbUser.setAttention(true);
									wbUser.setAttentionTime(new Date());
								}
								wbUserService.insert(wbUser);
								MQServer.getServer().publishMsg("sina.weibo", "sina", "follow", wbUser.getAddUrl());
							}
						}
					}
				}catch(Exception e){
				}
				Thread.sleep(30*1000);
			}
		}
	}

}
